var scripts = [null, '../assets/js/bootstrap-multiselect.js', "../assets/js/jquery.validate.js", '../assets/js/bootstrap-tagsinput.js', "../assets/js/jquery.validate_msgzh.js", "", null]
var focusIDs = [], lineIDs = [];

$('.page-content-area').ace_ajax('loadScripts', scripts, function () {

  jQuery(function ($) {
    var $areaId = $("#areaId");
    var $area2Id = $("#destinationId");
    $areaId.multiselect({
      enableFiltering: true,
      buttonClass: 'btn btn-white btn-primary',
      maxHeight: 200,
      numberDisplayed: 1,
      templates: {
        button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
        ul: '<ul class="multiselect-container dropdown-menu"></ul>',
        filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
        filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
        li: '<li><a href="javascript:void(0);"><label></label></a></li>',
        divider: '<li class="multiselect-item divider"></li>',
        liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
      },
      onChange: function (option, checked) {//change事件改变

        if ($utils.common.hasValue($areaId.val())) {
          getChildrenNode($areaId.val().join(","))
        } else {
          $area2Id.html("")
          $area2Id.multiselect("rebuild")
        }
      },
    });
    $area2Id.multiselect({
      enableFiltering: true,
      buttonClass: 'btn btn-white btn-primary',
      maxHeight: 200,
      numberDisplayed: 1,
      templates: {
        button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
        ul: '<ul class="multiselect-container dropdown-menu"></ul>',
        filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
        filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
        li: '<li><a href="javascript:void(0);"><label></label></a></li>',
        divider: '<li class="multiselect-item divider"></li>',
        liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
      }
    });
    var areaId = '1'   // "1" "3"
    var destinationId = ""  // '1,3'

    $('[data-rel=tooltip]').tooltip();
    $('.input-file').ace_file_input({
      no_file: '请选择excel文件',
      btn_choose: '选择',
      btn_change: '更改',
      droppable: false,
      onchange: null,
      thumbnail: false//| true | large
    });

    renderProductType('productType')
    renderActivityType('productActivityDiv')

    /*--------------------------基本信息操作---------------------------------*/

    $("#webuploader-pick").click(function () {
      resourceModel(1, 1, 2, function (data) {
        console.log(data)
        $(".mainImg").attr("src", data[0].src);
        $(".mainImg").attr("data-id", data[0].id);
      })
    })


    getBaseInfoData()

    function getBaseInfoData() {
      var url = $utils.ajax.setUrl("product/getProductById");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      axios.post(url, params)
        .then(function (response) {
          renderBaseinfoProduct(response.body)

          renderProductPrompt(response.body.productPrompt)
          renderProductUserInstructions(response.body.productUserInstructions)

        })
        .catch(function (error) {
        });
    }

    function renderBaseinfoProduct(body) {
      $("#productName").val(body.productName)
      $("#productTitle").val(body.productTitle)
      $("#productTitle1").val(body.productTitle1)
      $("#productSubTitle").val(body.productSubTitle)
      $("#productType").val(body.productType)
      $("#productSelfVipFlag").val(body.productSelfVipFlag)
      $("#productPrice").val(body.productPrice)

      $("#productCode").val(body.productCode)
      $("#productRoutePackage").html(body.productRoutePackage)
      $("#productFeature").val(body.productFeature)

      $("#productRoutePackageBlack").val(body.productRoutePackageBlack)
      $("#productRoutePackageRed").val(body.productRoutePackageRed)
      $('#productRoutePackageBlack').tagsinput('add', body.productRoutePackageBlack);
      $('#productRoutePackageRed').tagsinput('add', body.productRoutePackageRed);

      $("#productFeatureSpot").val(body.productFeatureSpot)
      $("#productServicePromise").val(body.productServicePromise)
      $("#productRoute").val(body.productRoute)
      $(".mainImg").attr("src", body.mainImageUrl);
      $(".mainImg").attr("data-id", body.resourceId);

      var productTypeRefArr = []
      var productTypeSortArr = []
      if (body.productTypeRef != null) {
        productTypeRefArr = body.productTypeRef.split(",")
        productTypeSortArr =body.productSort.split(",")
      }
      $("#hotSort").val("100")
      $("#recommendSort").val("100")
      if (productTypeRefArr.length > 0) {
        $.each(productTypeRefArr, function (key, val) {
          $('#productTypeRef input[value=' + val + ']').prop('checked', true)
          if(productTypeSortArr.length==1){
            if(val==1){
              $("#hotSort").val(productTypeSortArr[0])
            }else{
              $("#recommendSort").val(productTypeSortArr[0])
            }
          }else if(productTypeSortArr.length==2){
            if(val==1){
              $("#hotSort").val(productTypeSortArr[0])
            }else{
              $("#recommendSort").val(productTypeSortArr[1])
            }
          }
        })
      }
      $("#productFeatureSpot").val(body.productFeatureSpot)

      var productActivityArr = []
      if (body.productActivity != null) {
        productActivityArr = body.productActivity.split(",")
      }
      if (productActivityArr.length > 0) {
        $.each(productActivityArr, function (key, val) {
          $('#productActivityDiv input[value=' + val + ']').prop('checked', true)
        })
      }
      areaId = body.areaId   // '1,3'
      destinationId = body.destinationId  // '11,31,32,34'
      getChildrenNode(0)
    }

    function getChildrenNode(id) {
      var params = {}
      params.pId = id;
      var url = $utils.ajax.setUrl("destination/getDestinationByPid");
      axios.post(url, params)
        .then(function (response) {
          renderChildrenNode(id, response.body)
        })
    }

    function renderChildrenNode(id, list) {
      var html = ``;
      if (list.length > 0) {
        $.each(list, function (key, val) {
          html += `<option value="${val.DESTINATION_ID}">${val.DESTINATION_NAME}</option>`
        })
      }
      if (id == 0) {
        $areaId.html(html)
        $areaId.multiselect("rebuild")
        $areaId.multiselect('select', (areaId || "").split(","));

        if ($utils.common.hasValue(areaId)) {
          getChildrenNode(areaId)
        }
      } else {
        $area2Id.html(html)
        $area2Id.multiselect("rebuild")
        $area2Id.multiselect('select', (destinationId || "").split(","))

      }
    }

    $("#updateBaseInfo").click(function () {
      updateProductBaseInfo()
    })

    function updateProductBaseInfo() {
      var url = $utils.ajax.setUrl("product/updateProductById");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.productName = $("#productName").val()//产品名称
      params.productTitle = $("#productTitle").val()//
      params.productTitle1 = $("#productTitle1").val()//标题
      params.productSubTitle = $("#productSubTitle").val()//副标题
      params.productType = $("#productType").val()
      params.productSelfVipFlag = $("#productSelfVipFlag").val()
      params.productPrice = $("#productPrice").val()
      //params.areaId=$("#areaId").val()
      params.destinationId = ($("#destinationId").val() || []).join(",")
      params.productCode = $("#productCode").val()
      params.productFeatureSpot = $("#productFeatureSpot").val()
      //params.productRoutePackage = $("#productRoutePackage").html()
      params.productFeature = $("#productFeature").val()
      params.productServicePromise = $("#productServicePromise").val()
      params.productRoute = $("#productRoute").val()
      params.resourceId = $(".mainImg").attr("data-id")

      if ($(".mainImg").attr("data-id") == "") {
        alert("请添加主图")
        return
      }

      var productRoutePackageBlack = $("#productRoutePackageBlack").tagsinput('items')
      var productRoutePackageRed = $("#productRoutePackageRed").tagsinput('items')
      params.productRoutePackageBlack = productRoutePackageBlack.join(",")
      params.productRoutePackageRed = productRoutePackageRed.join(",")

      var productTypeRefArr = []

      params.hotSort=$("#hotSort").val()||"1000"
      params.recommendSort=$("#recommendSort").val()||"1000"
      var productTypeRefArr = []
      $("#productTypeRef input:checked").each(function (index, ele) {
        productTypeRefArr.push($(this).val())
      })
      if (productTypeRefArr.length > 0) {
        params.productTypeRef = productTypeRefArr.join(',')
      }

      var productActivityArr = []
      $("#productActivityDiv input:checked").each(function (index, ele) {
        productActivityArr.push($(this).val())
      })
      if (productActivityArr.length > 0) {
        params.productActivity = productActivityArr.join(',')
      }
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }


    /*--------------------------价格导入---------------------------------*/
    productPriceQueryList()

    function productPriceQueryList() {
      var url = $utils.ajax.setUrl("productPrice/queryList");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      axios.post(url, params)
        .then(function (response) {
          renderPriceListFromSever(response.body)
        })
    }

    function renderPriceListFromSever(body) {
      if (body.length > 0) {
        var html = ''
        $.each(body, function (key, val) {
          html += `<tr><td class="hidden-480"><input class="priceDate" type="text" value="${val.PRICE_DATE}"></td>
                        <td class="hidden-480"><input class="backDate" type="text" value="${val.BACK_DATE}"></td>
                        <td class="hidden-480"><input class="productPrice" type="text" value="${val.PRODUCT_PRICE != null ? val.PRODUCT_PRICE : ""}"></td>
                        <td class="hidden-480"><input class="childrenPrice" type="text" value="${val.CHILDREN_PRICE != null ? val.CHILDREN_PRICE : ""}"></td>
                        <td class="hidden-480"><input class="productRemainNumDay" type="text" value="${val.PRODUCT_REMAIN_NUM_DAY != null ? val.PRODUCT_REMAIN_NUM_DAY : ""}"></td>
                        <td class="hidden-480"><input class="priceDetail" type="text" value="${val.PRICE_DETAIL}"></td>
                        <td class="hidden-480">
                        <span class="btn btn-sm btn-warning" onclick="updateProductPriceDayById(this,${val.PRICE_ID})">修改</span>
                        <span class="btn btn-sm btn-warning" onclick="deleteProductPriceDayById(this,${val.PRICE_ID})">删除</span></td></tr>`
        })
        $(".priceTable tbody").html(html)
      }
    }


    $('#priceImport').click(function () {
      var path = $('#price-input-file').val();
      var formData = new FormData();

      if (!$("#price-input-file")[0].files[0]) {
        bootbox.alert("请选择需要导入的excel文件!");
        return;
      }

      formData.append("file", $("#price-input-file")[0].files[0]);
      formData.append("productId", $utils.string.getQueryParam("id"));
      var urlUploadFile = $utils.ajax.setUrl("productPrice/uploadProductPrice");
      $.ajax({
        url: urlUploadFile,
        type: "post",
        async: true,
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        success: function (data) {
          var result = JSON.parse(data)
          if (result.code == "10000") {
            bootbox.alert(result.msg)
            renderPriceList(result.body)
          } else {
            bootbox.alert(result.msg)
          }
        }
      });
    })

    /*导入价格*/

    function renderPriceList(list) {
      var html = ''
      $.each(list, function (key, val) {
        html += `<tr><td class="hidden-480"><input class="priceDate" type="text" value="${val.priceDate}"></td>
                        <td class="hidden-480"><input class="backDate" type="text" value="${val.backDate}"></td>
                        <td class="hidden-480"><input class="productPrice" type="text" value="${val.productPrice != null ? val.productPrice : ""}"></td>
                        <td class="hidden-480"><input class="childrenPrice" type="text" value="${val.childrenPrice != null ? val.childrenPrice : ""}"></td>
                        <td class="hidden-480"><input class="productRemainNumDay" type="text" value="${val.productRemainNumDay != null ? val.productRemainNumDay : ""}"></td>
                        <td class="hidden-480"><input type="text" value="${val.priceDetail}"></td>
                        <td class="hidden-480"><span class="btn btn-sm btn-warning" onclick="updateProductPriceDayById(this,${val.priceId})">修改</span>
                        <span class="btn btn-sm btn-warning" onclick="deleteProductPriceDayById(this,${val.priceId})">删除</span></td></tr>`
      })

      $(".priceTable tbody").html(html)
    }


    /*--------------------------费用说明操作---------------------------------*/

    $("#addFinerCost").click(function () {
      modelAddFinerCost(function (data) {
        var html = `<div class="space-2"></div><div class="form-group">
                <label class="control-label col-xs-12 col-sm-3 no-padding-right">【${data.t1}】 <i class="ace-icon glyphicon glyphicon-remove red2 cursor-p" onclick="removeItem(this)"></i></label>
                <div class="col-xs-12 col-sm-9">
                  <div class="clearfix">
                    <textarea class="col-sm-12" data-title="${data.t1}" describeIsContain="${data.t2}" ></textarea>
                  </div>
                </div>
              </div>`

        if (data.t2 == 1) {
          $("#IsContain").append(html)
        } else {
          $("#NotContain").append(html)
        }
      })
    })
    getProductCostData()

    function getProductCostData() {
      var url = $utils.ajax.setUrl("productCostDescribe/getProductCostDescribeByProductId");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      axios.post(url, params)
        .then(function (response) {
          renderProductCost(response.body)
        })
    }

    function renderProductCost(body) {
      $.each(body, function (key, val) {

        var html = ''
        var htm2 = ''

        $.each(body, function (key, val) {
          if (val.describeIsContain) {
            html += `<div class="space-2"></div><div class="form-group">
                <label class="control-label col-xs-12 col-sm-3 no-padding-right">【${val.describeTypeName}】 <i class="ace-icon glyphicon glyphicon-remove red2 cursor-p" onclick="removeItem(this)"></i></label>
                <div class="col-xs-12 col-sm-9">
                  <div class="clearfix">
                    <textarea class="col-sm-12" data-title="${val.describeTypeName}" describeIsContain="${val.describeIsContain}" >${val.describeTypeDetail}</textarea>
                  </div>
                </div>
              </div>`
          } else {
            htm2 += `<div class="space-2"></div><div class="form-group">
                <label class="control-label col-xs-12 col-sm-3 no-padding-right">【${val.describeTypeName}】 <i class="ace-icon glyphicon glyphicon-remove red2 cursor-p" onclick="removeItem(this)"></i></label>
                <div class="col-xs-12 col-sm-9">
                  <div class="clearfix">
                    <textarea class="col-sm-12" data-title="${val.describeTypeName}" describeIsContain="${val.describeIsContain}" >${val.describeTypeDetail}</textarea>
                  </div>
                </div>
              </div>`
          }
        })
        // $('.CostDescribe .editCost[describeIsContain=' + val.describeIsContain + '][describeSort=' + val.describeSort + ']').html(val.describeTypeDetail)
        $("#IsContain").html(html)
        $("#NotContain").html(htm2)
      })
    }

    $("#updateCost").click(function () {
      updateProductCostDescribe()
    })

    function updateProductCostDescribe() {
      var url = $utils.ajax.setUrl("productCostDescribe/addOrUpdateProductCostDescribe");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.list = []
      var productCostDescribes = []
      $('.CostDescribe textarea').each(function (index, ele) {
        productCostDescribes.push({
          "describeTypeName": $(ele).attr("data-title"),
          "describeIsContain": $(ele).attr("describeIsContain"),
          "describeSort": index,
          "describeTypeDetail": $(ele).val()
        })
      })
      params.list = productCostDescribes
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }

    /*--------------------------线路特色操作---------------------------------*/
    $("#webuploader-picks").click(function () {
      resourceModel(2, 1, 2, function (data) {
        console.log(data)
        $(".mainImg").attr("src", data[0].src);
        $(".mainImg").attr("data-id", data[0].id);
      })
    })

    getProductLineData()

    function getProductLineData() {
      var url = $utils.ajax.setUrl("productLineFeature/getProductLineFeatureByProductId");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      axios.post(url, params)
        .then(function (response) {
          renderProductLine(response.body)
        })
    }

    function renderProductLine(body) {
      $.each(body, function (key, val) {
        $('.lineFeature textarea[featureSort=' + val.featureSort + ']').val(val.featureTypeDetail)
      })
    }

    $("#updateLine").click(function () {
      updateProductLineFeature()
    })

    function updateProductLineFeature() {
      var url = $utils.ajax.setUrl("productLineFeature/addOrUpdateProductLineFeature");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      var productLineFeatures = []
      $('.lineFeature textarea').each(function (index, ele) {
        productLineFeatures.push({
          "featureTypeName": $(ele).attr("data-title"),
          "featureSort": $(ele).attr("featureSort"),
          "featureTypeDetail": $(ele).val()
        })
      })
      params.list = productLineFeatures
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }


    /*--------------------------参考交通操作---------------------------------*/


    getProductTrafficData()

    function getProductTrafficData() {
      var url = $utils.ajax.setUrl("productReferTraffic/getProductReferTrafficByProductId");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      axios.post(url, params)
        .then(function (response) {
          renderProductTraffic(response.body)
        })
    }

    function renderProductTraffic(body) {
      if (body.length > 0) {
        $("#startStation1").val(body[0].startStation)
        $("#endStation1").val(body[0].endStation)
        // $("#startDay1").val(body[0].startDay)
        // $("#endDay1").val(body[0].endDay)
        // $("#startTime1").val(body[0].startTime)
        // $("#endTime1").val(body[0].endTime)
        $("#trafficSumTime1").val(body[0].trafficSumTime)
        $("#trafficDetail1").val(body[0].trafficDetail)

        $("#startStation2").val(body[1].startStation)
        $("#endStation2").val(body[1].endStation)
        // $("#startDay2").val(body[1].startDay)
        // $("#endDay2").val(body[1].endDay)
        // $("#startTime2").val(body[1].startTime)
        // $("#endTime2").val(body[1].endTime)
        $("#trafficSumTime2").val(body[1].trafficSumTime)
        $("#trafficDetail2").val(body[1].trafficDetail)
      }
    }

    $("#updateTraffic").click(function () {
      addProductReferTraffic()
    })

    function addProductReferTraffic() {
      var url = $utils.ajax.setUrl("productReferTraffic/addOrUpdateProductReferTraffic");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      var productReferTraffics = []
      productReferTraffics.push({
        "goBackType": 1,
        "startStation": $("#startStation1").val(),
        "endStation": $("#endStation1").val(),
        "startDay": "",
        "endDay": "",
        "startTime": "",
        "endTime": "",
        "trafficSumTime": $("#trafficSumTime1").val(),
        "trafficDetail": $("#trafficDetail1").val()
      })
      productReferTraffics.push({
        "goBackType": 2,
        "startStation": $("#startStation2").val(),
        "endStation": $("#endStation2").val(),
        "startDay": "",
        "endDay": "",
        "startTime": "",
        "endTime": "",
        "trafficSumTime": $("#trafficSumTime2").val(),
        "trafficDetail": $("#trafficDetail2").val()
      })
      params.list = productReferTraffics
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }


    /*--------------------------参考行程---------------------------------*/
    var days = 1;
    $('#addOneDay').click(function () {
      var $clone = $(".Trip .day[data-day=" + days + "]").clone(true);
      var $wrapper = $('<div class="wrapper"></div>')
      $wrapper.html($clone)
      days++;
      $wrapper.find(".d").html(days)
      $wrapper.find(".day").attr("data-day", days)
      $('.Trip .days').append($wrapper.html())
    })

    $('#subtractTastDay').click(function () {
      var day = $('.Trip .days>div.day:last').attr("data-day")
      if (day == 1) {
        bootbox.alert("第一天不能删除")
      } else {
        $('.Trip .days>div.day:last').remove()
        days--;
      }
    })

    getProductRouteData()

    function getProductRouteData() {
      var url = $utils.ajax.setUrl("productReferRoute/getProductReferRouteByProductId");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      axios.post(url, params)
        .then(function (response) {
          renderProductRoute(response.body)
        })
    }

    function renderProductRoute(body) {
      days = body.length;
      var html = '';
      if (days > 0) {
        $.each(body, function (key, val) {
          var STAGE_NAME = val.STAGE_NAME.split("--");
          //var Settime = val.detailList[0].DETAIL_TYPE_DETAIL.split("******");//集合信息
          var Food = val.detailList[1].DETAIL_TYPE_DETAIL.split("******"); //甄选美食
          var Hotel = val.detailList[2].DETAIL_TYPE_DETAIL; //酒店住宿HotelHotelHotel
          var Tourist = val.detailList[3].DETAIL_TYPE_DETAIL; //游览景点
          var Itinerary = val.detailList[4].DETAIL_TYPE_DETAIL; //行程

          html += '<div class="day" data-day="' + val.STAGE_ID_SORT + '">' +
            '                    <div class="timeline-container">' +
            '                      <div class="timeline-label">' +
            '                                            <span class="label label-primary arrowed-in-right label-lg">第<b' +
            '                                              class="d">' + val.STAGE_ID_SORT + '</b>天</span>' +
            '                      </div>' +
            '                      <div class="timeline-items">' +
            '                        <div class="timeline-item clearfix">' +
            '                          <div class="timeline-info">' +
            '                            <i class="timeline-indicator ace-icon fa fa-cutlery btn btn-success no-hover"></i>' +
            '                          </div>' +
            '                          <div class="widget-box transparent">' +
            '                            <div class="widget-header widget-header-small">' +
            '                              <h5 class="widget-title smaller">' +
            '                                <span class="blue">行程/甄选美食/酒店</span>' +
            '                              </h5>' +
            '                            </div>' +
            '                            <div class="widget-body">' +
            '                              <div class="widget-main clearfix">' +
            '                                <form class="form-horizontal" role="form">' +
            '                                  <div class="clearfix">' +
            '                                    <div class="col-sm-3">' +
            '                                      <div class="form-group">' +
            '                                        <label class="col-sm-3 control-label no-padding-right">出发地点</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <input type="text" data="11" value="' + STAGE_NAME[0] + '"' +
            '                                                 class="col-sm-10">' +
            '                                        </div>' +
            '                                      </div>' +
            '                                    </div>' +
            '                                    <div class="col-sm-3">' +
            '                                      <div class="form-group">' +
            '                                        <label class="col-sm-3 control-label no-padding-right">终点</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <input type="text" data="12" value="' + STAGE_NAME[1] + '"' +
            '                                                 class="col-sm-10">' +
            '                                        </div>' +
            '                                      </div>' +
            '                                    </div>' +
            '                                  </div>' +
            '                                  <div class="clearfix">' +
            '                                    <div class="col-sm-3">' +
            '                                      <div class="form-group">' +
            '                                        <label class="col-sm-3 control-label no-padding-right">早餐</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <input type="text" data="13" value="' + Food[0].substr(3) + '"' +
            '                                                 class="col-sm-10">' +
            '                                        </div>' +
            '                                      </div>' +
            '                                    </div>' +
            '                                    <div class="col-sm-3">' +
            '                                      <div class="form-group">' +
            '                                        <label class="col-sm-3 control-label no-padding-right">午餐</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <input type="text" data="14" value="' + Food[1].substr(3) + '"' +
            '                                                 class="col-sm-10">' +
            '                                        </div>' +
            '                                      </div>' +
            '                                    </div>' +
            '                                    <div class="col-sm-3">' +
            '                                      <div class="form-group">' +
            '                                        <label class="col-sm-3 control-label no-padding-right">晚餐</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <input type="text" data="15" value="' + Food[2].substr(3) + '"' +
            '                                                 class="col-sm-10">' +
            '                                        </div>' +
            '                                      </div>' +
            '                                    </div>' +
            '                                  </div>' +
            '                                  <div class="clearfix">' +
            '                                    <div class="col-sm-3">' +
            '                                      <div class="form-group">' +
            '                                        <label class="col-sm-3 control-label no-padding-right">酒店类型</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <input type="text" data="17" class="col-sm-10" value="' + Hotel + '">' +
            '                                        </div>' +
            '                                      </div>' +
            '                                    </div>' +
            '                                  </div>' +
            '                                </form>' +
            '                              </div>' +
            '                            </div>' +
            '                          </div>' +
            '                        </div>' +
            '                        <div class="timeline-item clearfix">' +
            '                          <div class="timeline-info">' +
            '                            <i class="timeline-indicator ace-icon fa fa-star btn btn-warning no-hover green"></i>' +
            '                          </div>' +
            '                          <!-- /section:pages/timeline.info -->' +
            '                          <div class="widget-box transparent">' +
            '                            <div class="widget-header widget-header-small">' +
            '                              <h5 class="widget-title smaller">' +
            '                                <span class="blue">旅游景点/行程介绍</span>' +
            '                              </h5>' +
            '                            </div>' +
            '                            <div class="widget-body">' +
            '                              <div class="widget-main clearfix">' +
            '                                <form class="form-horizontal" role="form">' +
            '                                  <div class="col-sm-12">' +
            '                                    <div class="form-group">' +
            '                                      <div class="clearfix">' +
            '                                        <label class="col-sm-1 control-label no-padding-right">旅游景点</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <textarea class="col-sm-12" data="31">' + Tourist + '</textarea>' +
            '                                        </div>' +
            '                                      </div>' +
            '                                      <div class="space-8"></div>' +
            '                                      <div class="clearfix">' +
            '                                        <label class="col-sm-1 control-label no-padding-right">行程介绍</label>' +
            '                                        <div class="col-sm-9">' +
            '                                          <textarea class="col-sm-12" data="32">' + Itinerary + '</textarea>' +
            '                                        </div>' +
            '                                      </div>' +
            '                                    </div>' +
            '                                  </div>' +
            '                                </form>' +
            '                              </div>' +
            '                            </div>' +
            '                          </div>' +
            '                        </div>' +
            '                      </div>' +
            '                    </div>' +
            '                  </div>'
        })
        $('#route .days').html(html)
      } else {
        days = 1
      }
    }

    $("#updateRoute").click(function () {
      addProductReferRoute()
    })

    function addProductReferRoute() {
      var url = $utils.ajax.setUrl("productReferRoute/addOrUpdateProductReferRoute");
      var params = {}
      params.productId = $utils.string.getQueryParam("id");
      params.list = []

      $('.Trip .day').each(function (index, ele) {
        var item = {}
        item.stageIdSort = $(this).attr("data-day")
        item.stageName = $(this).find("input[data=11]").val() + '--' + $(this).find("input[data=12]").val()
        item.productReferRouteDetails = [{}, {}, {}, {}, {}]
        item.productReferRouteDetails[0].referSort = 1
        item.productReferRouteDetails[0].detailTypeName = '集合时间'
        item.productReferRouteDetails[0].detailTypeDetail = '集合时间:' + "" + '******' +
          '集合地点:' + "";


        item.productReferRouteDetails[1].referSort = 2
        item.productReferRouteDetails[1].detailTypeName = '甄选美食'
        item.productReferRouteDetails[1].detailTypeDetail = '早餐:' + $(this).find("input[data=13]").val() + '******' +
          '午餐:' + $(this).find("input[data=14]").val() + '******' +
          '晚餐:' + $(this).find("input[data=15]").val();


        item.productReferRouteDetails[2].referSort = 3
        item.productReferRouteDetails[2].detailTypeName = '酒店住宿'
        item.productReferRouteDetails[2].detailTypeDetail = $(this).find("input[data=17]").val();

        item.productReferRouteDetails[3].referSort = 4
        item.productReferRouteDetails[3].detailTypeName = '游览景点'
        item.productReferRouteDetails[3].detailTypeDetail = $(this).find("textarea[data=31]").val();


        item.productReferRouteDetails[4].referSort = 5
        item.productReferRouteDetails[4].detailTypeName = '行程介绍'
        item.productReferRouteDetails[4].detailTypeDetail = $(this).find("textarea[data=32]").val();

        params.list.push(item)
      })
      axios.post(url, params).then(function (response) {
        bootbox.alert("修改完成")
      })
    }


    /*------------------------温馨提示---------------------------------------*/

    function renderProductPrompt(productPrompt) {
      $('#productPrompt').val(productPrompt)
    }

    $("#updatePrompt").click(function () {
      addOrUpdateProductPrompt()
    })

    function addOrUpdateProductPrompt() {
      var url = $utils.ajax.setUrl("product/addOrUpdateProductPrompt");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.productPrompt = $('#productPrompt').val()
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }

    /*------------------------用户须知---------------------------------------*/

    function renderProductUserInstructions(productUserInstructions) {
      $('#UserInstructions').val(productUserInstructions)
    }

    $("#updateUserInstructions").click(function () {
      addOrUpdateProductUserInstructions()
    })

    function addOrUpdateProductUserInstructions() {
      var url = $utils.ajax.setUrl("product/addOrUpdateProductUserInstructions");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.productUserInstructions = $('#UserInstructions').val()
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }

    /*--------------------------图片操作---------------------------------*/

    queryProductImageList()

    function queryProductImageList() {
      var url = $utils.ajax.setUrl("product/queryProductImageList");
      var params = {}
      params.productId = parseInt($utils.string.getQueryParam("id"));
      axios.post(url, params)
        .then(function (response) {
          renderProductImageList(response.body)
        })
    }

    function renderProductImageList(body) {
      if (body.length > 0) {
        var htmlfocus = ''
        var htmlline = ''
        $.each(body, function (key, val) {
          if (val.FIRST_FLAG == 2) {
            focusIDs.push(String(val.RESOURCE_ID))
            htmlfocus += '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.RESOURCE_ID + '"' + 'src="' + val.IMAGE_URL + '">' +
              '<span onclick="delProductImg(this,' + 1 + ')" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
          } else if (val.FIRST_FLAG == 3) {
            lineIDs.push(String(val.RESOURCE_ID))
            htmlline += '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.RESOURCE_ID + '"' + 'src="' + val.IMAGE_URL + '">' +
              '<span onclick="delProductImg(this,' + 2 + ')" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
          }
        })
        $("#productImgs .imgslist-focus").html(htmlfocus)
        $("#productImgs .imgslist-line").html(htmlline)
      }
    }


    /**产品焦点图*/

    $("#webuploader-pick-focus").click(function () {
      resourceModel(2, 1, 2, function (data) {

        $.each(data, function (key, val) {
          if ($.inArray(val.id, focusIDs) == -1) {
            focusIDs.push(val.id);
            var html = '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
              '<span onclick="delProductImg(this,1)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
            $("#productImgs .imgslist-focus").append(html)
          }
        })
      })
    })

    /**产品旅行图*/
    $("#webuploader-pick-line").click(function () {
      resourceModel(2, 1, 2, function (data) {
        $.each(data, function (key, val) {
          if ($.inArray(val.id, lineIDs) == -1) {
            lineIDs.push(val.id);
            var html = '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
              '<span onclick="delProductImg(this,2)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
            $("#productImgs .imgslist-line").append(html)
          }
        })
      })
    })

    $("#updateProductImgs").click(function () {
      addProductImage()
    })


    function addProductImage() {
      var url = $utils.ajax.setUrl("product/updateProductImage");
      var params = {}
      params.productId = $utils.string.getQueryParam("id");
      if (focusIDs.length > 0) {
        params.resourceProductIds = focusIDs.join(",")
      } else {
        params.resourceProductIds = ""
      }
      if (lineIDs.length > 0) {
        params.resourceProductLineFeatureIds = lineIDs.join(",")
      } else {
        params.resourceProductLineFeatureIds = ""
      }

      axios.post(url, params)
        .then(function (response) {
          bootbox.alert("添加产品完成")
          window.location.href = "#page/product/list"
        })
    }


    /*--------------------------评论操作---------------------------------*/
    getproductComment(1)

    function getproductComment(page) {
      var url = $utils.ajax.setUrl("productComment/queryList");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.page = page
      params.rows = 3
      axios.post(url, params)
        .then(function (response) {
          renderComment(response.body)
        })
        .catch(function (error) {
        });
    }

    var page = 1;
    $(window).scroll(function () {
      //$(window).scrollTop()这个方法是当前滚动条滚动的距离
      //$(window).height()获取当前窗体的高度
      //$(document).height()获取当前文档的高度
      if ($("#tabComment").hasClass("active")) {
        if (($(window).scrollTop()) >= ($(document).height() - $(window).height()) * 0.9) {
          page++
          getproductComment(page)
        }
      }
    });

    function renderComment(body) {
      var html = '';
      console.log(body.rows.length)
      if (body.rows.length > 0) {
        $.each(body.rows, function (key, val) {
          html += '<li data-content-id="' + val.COMMENT_ID + '" class="clearfix item">' +
            '                    <div class="left">' +
            '                      <img class="userImg" src="' + val.userInfo.IMAGE_URL + '" alt="">' +
            '                    </div>' +
            '                    <div class="right">' +
            '                      <div class="header">' +
            '                        <p class="name">' + val.userInfo.BUSER_NAME + '</p>' +
            '                        <p class="time">' + moment(val.CREATE_TIME).format("YYYY-MM-DD HH:mm:ss") + '</p>' +
            '                        <p class="desc">' + val.COMMENT_TEXT +
            '                        <span class="del" onclick="CommentDel(' + val.COMMENT_ID + ')"><icon class="ace-icon fa fa-trash-o red bigger-150 cursor-p tt-cursor"></icon>删除</span>' +
            '                      </div>';
          if (val.imageList.length > 0) {
            html += '<ul class="imgList clearfix no-margin">';
            $.each(val.imageList, function (ckey, cval) {
              html += '<li class="img-item"><img' +
                ' src="' + cval.DOMAIN_NAME + cval.RESOURCE_URL + cval.RESOURCE_NAME + '"' +
                ' alt=""></li>'
            })
            html += '</ul>';
          }
          html += '</div>' +
            '</li>'
        })
      }
      $('#comment .list').append(html)
    }
  });
});

function CommentDel(id) {
  bootbox.confirm("确认删除吗", function (v) {
    if (v) {
      var url = $utils.ajax.setUrl("productComment/deleteProductCommentById");
      var params = {}
      params.commentId = id;
      axios.post(url, params)
        .then(function (response) {
          $(".item[data-content-id=" + id + "]").remove()
        })
    }
  })
}

function delProductImg(obj, type) {
  $(obj).parents(".item").remove()
  if (type == 1) {
    removeArrItem(focusIDs, $(obj).prev("img").attr("data-id"))
  }
  if (type == 2) {
    removeArrItem(lineIDs, $(obj).prev("img").attr("data-id"))
  }
}

function removeItem(obj) {
  $(obj).parents(".form-group").remove()
}

function updateProductPriceDayById(obj, priceId) {
  bootbox.confirm("确认修改吗", function (v) {
    if (v) {
      var url = $utils.ajax.setUrl("productPrice/updateProductPriceDayById");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.priceId = priceId;
      params.priceDate = $(obj).parents('tr').find(".priceDate").val()
      params.backDate = $(obj).parents('tr').find(".backDate").val()
      params.productPrice = $(obj).parents('tr').find(".productPrice").val();
      params.childrenPrice = $(obj).parents('tr').find(".childrenPrice").val();
      params.productRemainNumDay = $(obj).parents('tr').find(".productRemainNumDay").val();
      params.priceDetail = $(obj).parents('tr').find(".priceDetail").val();
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
        })
    }
  })
}

function deleteProductPriceDayById(obj, priceId) {
  bootbox.confirm("确认删除吗", function (v) {
    if (v) {
      var url = $utils.ajax.setUrl("productPrice/deleteProductPriceDayById");
      var params = {}
      params.productId = $utils.string.getQueryParam("id")
      params.priceId = priceId;
      axios.post(url, params)
        .then(function (response) {
          bootbox.alert(response.msg)
          if (response.code == '10000') {
            $(obj).parents("tr").remove()
          }
        })
    }
  })
}
